<?php

class Damages_Methods_Request_SetCarRelatedDamage extends Damages_Methods_Request {

  /**
   *
   * @var int
   */
  public $id;

  /**
   *
   * @var int
   */
  public $relatedDamageId;

  public function __construct($params) {
    parent::__construct($params);
    $this->id = (int) $params->id;
    $this->relatedDamageId = (int) $params->relatedDamageId;
  }

  public function process() {
    // powiązanie szkody magazynowej

    if (!Damages_Auth::getInstance()->checkPermission(array(Damages_Auth::PERMISSION_LS, Damages_Auth::PERMISSION_ADMIN)))
      throw new Damages_Exception_App(Damages_Codes::ACCESS_DENIED);
    $carDamage = $this->getDbObject();
    if (!$carDamage)
      throw new Damages_Exception_App(Damages_Codes::DB_OBJECT_NOT_FOUND);
    $this->validate();
    $carDamage->setRelatedCarDamage($this->relatedDamageId);
    $carDamage->save();
    $relatedCarDamage = DamagesCarDamagesQuery::create()->findOneById($this->relatedDamageId);
    $closedStatus = DamagesDictStatusesQuery::create()->findOneByCode(DamagesDictStatuses::CODE_NOT_ACCEPTED_CLOSED);
    $relatedCarDamage->setStatusId($closedStatus->getId());
    $relatedCarDamage->save();
    
    $response = new Damages_Methods_Response(true);
    return $response;
  }

  /**
   * 
   * @return DamagesCarDamages
   */
  private function getDbObject() {
    $data = DamagesCarDamagesQuery::create()->findOneById($this->id);
    return $data;
  }

  private function validate() {
    $relatedCarDamage = DamagesCarDamagesQuery::create()
            ->joinProcessTypes()
            ->with('ProcessTypes')
            ->findOneById($this->relatedDamageId);
    if (!$relatedCarDamage)
      throw new Damages_Exception_App(Damages_Codes::DB_OBJECT_NOT_FOUND);
    if ($relatedCarDamage->getProcessTypes()->getCode() != DamagesProcessTypes::CODE_WAREHOUSE)
      throw new Damages_Exception_App(Damages_Codes::INCORRECT_RELATED_CAR_DAMAGE);
  }

}